package com.zx.idc.backend.gui.api.ws.services.handler.strategy;

import com.zx.idc.backend.gui.api.commom.entity.CommandModel;
import com.zx.idc.backend.gui.api.ws.services.handler.strategy.command.base.CommandType;
import com.zx.idc.backend.gui.api.ws.services.handler.strategy.command.commandtype.OtherExceptionImpl;
import com.zx.idc.backend.gui.api.ws.services.handler.strategy.entity.Option;
import com.zx.idc.common.spring.SpringBeanUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * Created by hasee on 2019/2/21.
 */
@Component
public class CommandTypeContext {
    private static Map<String, CommandType> beansOfType;

    @PostConstruct
    public void init() {
        setBeansOfType(SpringBeanUtil.getBeansOfType(CommandType.class));
    }

    private static void setBeansOfType(Map<String, CommandType> beansOfType) {
        CommandTypeContext.beansOfType = beansOfType;
    }

    /**
     * 根据条件执行相应指令
     *
     * @param a            指令类型 非首级命令设置为-1
     * @param dataXml      指令xml数据
     * @param commandModel 指令接口实体
     * @return 结果
     */
    public String execute(int a, String dataXml, CommandModel commandModel) {
        Option option = new Option().setType(a).setXmlData(dataXml);
        return beansOfType.values().stream()
                .filter((commandTypeEntry) -> commandTypeEntry.isMatch(option))
                .findFirst()
                .orElse(new OtherExceptionImpl())
                .execute(dataXml, commandModel);
    }
}
